<template>
    <div ref="chartEl" class="chart-container"></div>
  </template>
  
  <script setup lang="ts">
  import { ref, onMounted, watch, onUnmounted } from 'vue'
  import * as echarts from 'echarts'
  
  // 定义props类型
  interface PieData {
    name: string
    value: number
  }
  
  const props = defineProps<{
    chartData: {
      categories: string[]
      data: PieData[]
    }
  }>()
  
  const chartEl = ref<HTMLElement>()
  let chart: echarts.ECharts | null = null
  
  onMounted(() => {
    if (chartEl.value) {
      chart = echarts.init(chartEl.value)
      updateChart()
    }
  })
  
  // 监听窗口变化
  const handleResize = () => chart?.resize()
  window.addEventListener('resize', handleResize)
  onUnmounted(() => window.removeEventListener('resize', handleResize))
  
  watch(() => props.chartData, updateChart, { deep: true })
  
  function updateChart() {
    if (!chart) return
  
    const option = {
      tooltip: {
        trigger: 'item',
        formatter: '{b}: {c} ({d}%)'
      },
      legend: {
        bottom: '5%',
        left: 'center',
        icon: 'circle',
        itemWidth: 10,
        itemHeight: 10
      },
      series: [
        {
          name: '能源结构',
          type: 'pie',
          radius: ['40%', '70%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 6,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: false,
            position: 'center'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: 16,
              fontWeight: 'bold'
            }
          },
          data: props.chartData.data
        }
      ],
      color: ['#36a2eb', '#4bc0c0', '#ff9f40', '#ff6384']
    }
  
    chart.setOption(option)
  }
  </script>
  
  <style scoped>
  .chart-container {
    width: 100%;
    height: 100%;
    min-height: 300px;
  }
  </style>